package com.xkdx.caipiao.fragment;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.xkdx.caipiao.CashRequestActivity;
import com.xkdx.caipiao.CompleteUserInfoActivity;
import com.xkdx.caipiao.MainTabActivity;
import com.xkdx.caipiao.MyLotterActivity;
import com.xkdx.caipiao.R;
import com.xkdx.caipiao.RechargeActivity;
import com.xkdx.caipiao.TelActivity;
import com.xkdx.caipiao.ThreadActivity;
import com.xkdx.caipiao.module.network.AbsModule;
import com.xkdx.caipiao.my.MyAccountActivity;
import com.xkdx.caipiao.my.OrderDetailsActivity;
import com.xkdx.caipiao.presistence.historyquery.HistoryQueryAction;
import com.xkdx.caipiao.presistence.historyquery.HistoryQueryInfo;
import com.xkdx.caipiao.presistence.historyquery.HistoryQueryModule;
import com.xkdx.caipiao.presistence.historyquery.HistoryQueryPresistence;
import com.xkdx.caipiao.presistence.hongbao.HongbaoInfo;
import com.xkdx.caipiao.presistence.login.Login;
import com.xkdx.caipiao.presistence.login.LoginInfo;
import com.xkdx.caipiao.redpacke.BuyRedpacketList;
import com.xkdx.caipiao.redpacke.RedPackeDetail;
import com.xkdx.caipiao.statics.IConstants;
import com.xkdx.caipiao.util.AESEncryptorUtils;
import com.xkdx.caipiao.util.Md5Utils;
import com.xkdx.caipiao.util.SharePrefenceUtil;

public class UserInfoFragment extends BaseFragment implements
		OnPageChangeListener, OnClickListener {
	private static String TAG = "UserInfoFragment";

	public static boolean isUpdate = false;
	View view;
	TextView title_info, red_detail, buy_lottery_tip, account;
	ViewPager viewPager;
	LinearLayout ll;
	

	HistoryQueryAction action;
	HistoryQueryModule module;
	HistoryQueryPresistence presistence;
	
	ListView lv_all, lv_no_open, lv_win;
	View view_all, view_no_open, view_win;
	List<View> viewList;
	List<HistoryQueryInfo> list, list_win, list_no_open;
	List<HongbaoInfo> list1;

	Drawable im_bottom;
	TextView tv_all, tv_win, tv_no_open,yuan;
	TextView tv_balance, tv_red_packet,tv_point, tv_name, tv_tel, tv_wanshan;
	Button btn_recharge, btn_withdraw_cash;
	LoginInfo info;
	HongbaoInfo info1;
	float money;
	
	Button redpacke;
	int clickpage;
	//true：当前是获取红包 ； false：获取订单列表
	boolean isGetRedpacket;
	
	//避免每次进入该页面时重复请求 -------现在每次进入该页面OnResuem被调用2次。
	boolean isFirstGetPacket;
	//避免每次进入该页面时重复请求 -------现在每次进入该页面OnResuem被调用2次。
	boolean isSending;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		info = new LoginInfo();
		im_bottom = getResources().getDrawable(R.drawable.viewpagger_line_caipiao);
		im_bottom.setBounds(0, 0, im_bottom.getMinimumWidth(),
				im_bottom.getMinimumHeight());

	}


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (view == null) {
			view = inflater.inflate(R.layout.user_info_caipiao, container, false);
			findView();
			account.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//给textview添加下划线
			red_detail.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
			setonClick();
			
		}

		// 缓存的view需要判断是否已经被加过parent，
		// 如果有parent需要从parent删除，要不然会发生这个view已经有parent的错误。

		ViewGroup parent = (ViewGroup) view.getParent();
		if (parent != null) {
			parent.removeView(view);
		}

		return view;

	}

	private void setonClick() {
		tv_all.setOnClickListener(this);
		tv_win.setOnClickListener(this);
		tv_no_open.setOnClickListener(this);
		tv_tel.setOnClickListener(this);
		btn_recharge.setOnClickListener(this);
		btn_withdraw_cash.setOnClickListener(this);

		red_detail.setOnClickListener(this);
		account.setOnClickListener(this);
		tv_wanshan.setOnClickListener(this);
		buy_lottery_tip.setOnClickListener(this);
		
		//红包的监听
		redpacke.setOnClickListener(this);
	}

	private void findView() {
		tv_all = (TextView) view.findViewById(R.id.text1);
		tv_win = (TextView) view.findViewById(R.id.text2);
		tv_no_open = (TextView) view.findViewById(R.id.text3);
		tv_balance = (TextView) view.findViewById(R.id.balance);
		tv_red_packet = (TextView) view.findViewById(R.id.red_packet);
		//tv_point = (TextView) view.findViewById(R.id.point);
		tv_name = (TextView) view.findViewById(R.id.login_success_name);
		tv_tel = (TextView) view.findViewById(R.id.tel);
		buy_lottery_tip = (TextView) view.findViewById(R.id.buy_lottery_tip);
		account = (TextView) view.findViewById(R.id.account);
		ll = (LinearLayout) view.findViewById(R.id.ll_buy_lottery);
		
		
		red_detail = (TextView) view.findViewById(R.id.red_detail);

		tv_wanshan = (TextView) view.findViewById(R.id.login_success_wanshan);

		btn_recharge = (Button) view.findViewById(R.id.btn_success_chongzhi);
		btn_withdraw_cash = (Button) view.findViewById(R.id.btn_success_tixian);

		viewPager = (ViewPager) view.findViewById(R.id.vPager);
		LayoutInflater lf = LayoutInflater.from(MyLotterActivity.context);
		list_win = new ArrayList<HistoryQueryInfo>();
		list_no_open = new ArrayList<HistoryQueryInfo>();

		view_all = lf.inflate(R.layout.all_order_caipiao, null);
		view_no_open = lf.inflate(R.layout.noopen_order_caipiao, null);
		view_win = lf.inflate(R.layout.win_order_caipiao, null);

		viewList = new ArrayList<View>();// 将要分页显示的View装入数组中
		viewList.add(view_all);
		viewList.add(view_win);
		viewList.add(view_no_open);

		lv_all = (ListView) view_all.findViewById(R.id.all_order_ls);
		lv_no_open = (ListView) view_no_open
				.findViewById(R.id.no_open_order_ls);
		lv_win = (ListView) view_win.findViewById(R.id.win_order_ls);

		viewPager.setAdapter(new adapter());
		viewPager.setCurrentItem(0);
		viewPager.setOnPageChangeListener(this);

		title_info = (TextView) view.findViewById(R.id.title_info);
		title_info.setText("注册");
		title_info.setVisibility(View.GONE);
		IConstants.hideInputMethodAways(MyLotterActivity.context, title_info);
		
		//红包
		redpacke = (Button) view.findViewById(R.id.red_packe);

	}

	@Override
	public void showOnPost(HashMap<String, AbsModule> result) {
		dataLoadDialog.dismiss();
		isSending = false;
		if (result.containsKey("0")) {
		
				info = ((ThreadActivity) getActivity()).getLoginInfo();
				if (info != null) {
					if (info.getVerify().equals("1")) {
						tv_wanshan.setVisibility(View.INVISIBLE);
					} else {
						tv_wanshan.setVisibility(View.VISIBLE);
					}

					if (IConstants.localUserMoney != 0) {
						DecimalFormat df = new DecimalFormat("#0.00");
						String st = df.format(IConstants.localUserMoney);
						tv_balance.setText(st);

					} else {
						if (!(TextUtils.isEmpty(info.getMoney()))) {

							float money = Float.valueOf(info.getMoney()) / 100;
							DecimalFormat df = new DecimalFormat("#0.00");
							String st = df.format(money);
							if ("0.00".equals(st)) {
								tv_balance.setText("0");
							} else {
								tv_balance.setText(st);
							}

						} else {
							tv_balance.setText("0");
						}
					}

					String nick = ("").equals(info.getUser_nickname()) ? info
							.getUser_login_name() : info.getUser_nickname();

					tv_name.setText(nick);
				}
				
				list1 = module.list1;
				if (list1.size() > 0) {
					tv_red_packet.setText(String.valueOf(list1.size()));
				}
				
				
				list = module.list;
				if (list != null && list.size() > 0) {
					viewPager.setVisibility(View.VISIBLE);
					buy_lottery_tip.setVisibility(View.GONE);
					setList();
				} else {
					viewPager.setVisibility(View.GONE);
					buy_lottery_tip.setVisibility(View.VISIBLE);
				}
		} else {
			if (getActivity() != null) {
				SharePrefenceUtil su = new SharePrefenceUtil(getActivity(),
						SharePrefenceUtil.USERINFO);
				su.clear();
				MyLotterActivity.loginInfo = null;
				IConstants.localUserMoney = 0;
				Intent intent = new Intent(getActivity(), Login.class);
				startActivity(intent);
			}
		}
	}

	private void setList() {
		if(list_no_open != null && list_no_open.size() > 0){
			list_no_open.clear();
		}
		if(list_win != null && list_win.size() > 0){
			list_win.clear();
		}
		for (HistoryQueryInfo info : list) {
			if (info.getStatus().equals("0")) {
					list_no_open.add(info);
			}
			if (info.getStatus().equals("2")) {
				list_win.add(info);
			}
		
		}
		listAdapter adapter = new listAdapter(list);
		lv_all.setAdapter(adapter);
		lv_all.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {

				Intent intent = new Intent(MyLotterActivity.context,
						OrderDetailsActivity.class);
				intent.putExtra("orderid", list.get(position).getOrderid());

				startActivity(intent);
			}
		});
		listAdapter noOpenadapter = new listAdapter(list_no_open);
		lv_no_open.setAdapter(noOpenadapter);

		lv_no_open.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {

				Intent intent = new Intent(MyLotterActivity.context,
						OrderDetailsActivity.class);
				intent.putExtra("orderid", list_no_open.get(position).getOrderid());

				startActivity(intent);
			}
		});
		listAdapter winAdapter = new listAdapter(list_win);
		lv_win.setAdapter(winAdapter);
		lv_win.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {

				Intent intent = new Intent(MyLotterActivity.context,
						OrderDetailsActivity.class);
				intent.putExtra("orderid", list_win.get(position).getOrderid());

				startActivity(intent);
			}
		});
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		info = ((ThreadActivity) getActivity()).getLoginInfo();
		if(!isSending && info !=null ){
			startThread();
		}
		if (isUpdate) {
			isUpdate = false;
		} else {
			info = ((ThreadActivity) getActivity()).getLoginInfo();
			if (info != null) {
				if (info.getVerify().equals("1")) {
					tv_wanshan.setVisibility(View.INVISIBLE);
				} else {
					tv_wanshan.setVisibility(View.VISIBLE);
				}

				if (IConstants.localUserMoney != 0) {
					DecimalFormat df = new DecimalFormat("#0.00");
					String st = df.format(IConstants.localUserMoney);
					tv_balance.setText(st);

				} else {
					if (!(TextUtils.isEmpty(info.getMoney()))) {
						
						float money = Float.valueOf(info.getMoney()) / 100;
						DecimalFormat df = new DecimalFormat("#0.00");
						String st = df.format(money);
						//money = Float.parseFloat(info.getMoney()) / 100;
						if ("0.00".equals(st)) {
							tv_balance.setText("0");
						}else {
							tv_balance.setText(st);
						}
					} else {
						tv_balance.setText("0");
					}
				}


				String nick = ("").equals(info.getUser_nickname()) ? info
						.getUser_login_name() : info.getUser_nickname();

				tv_name.setText(nick);

			}
		}

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {

		super.onActivityCreated(savedInstanceState);

	}

	@Override
	public void startThread() {
		isSending = true;
		if (!(dataLoadDialog.isShowing())) {
			dataLoadDialog.show();
			dataLoadDialog.setContentView(R.layout.progressbar_caipiao);
		}
		
		//解密
		String id = MyLotterActivity.loginInfo.getId();
		try {
			id = AESEncryptorUtils.decrypt("270922", id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String Logintoken = MyLotterActivity.loginInfo.getLogintoken();
		//Log.i(TAG, Logintoken);
		try {
			Logintoken = AESEncryptorUtils.decrypt("270922", Logintoken);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String md5 = id+Logintoken+IConstants.key;
		String signcode = Md5Utils.md5(md5);
		action = new HistoryQueryAction(id,
				Logintoken, "all", "1", "1000",signcode);
		module = new HistoryQueryModule(this);
		presistence = new HistoryQueryPresistence(this);
		presistence.setActitons(action);
		presistence.setModule(module);
		presistence.execute();
		

	}

	class adapter extends PagerAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return 3;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// TODO Auto-generated method stub
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {

			container.removeView(viewList.get(position));

		}

		@Override
		public int getItemPosition(Object object) {
			// TODO Auto-generated method stub
			return super.getItemPosition(object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(viewList.get(position));// 添加页卡
			return viewList.get(position);
		}

	}

	class listAdapter extends BaseAdapter {
		List<HistoryQueryInfo> list;
		private DecimalFormat df;

		public listAdapter(List<HistoryQueryInfo> list) {
			// TODO Auto-generated constructor stub
			this.list = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int position, View convertview, ViewGroup arg2) {
			viewHolder holder;
			if (convertview == null) {
				holder = new viewHolder();
				convertview = LayoutInflater.from(MyLotterActivity.context)
						.inflate(R.layout.order_query_item_caipiao, null);
				holder.name = (TextView) convertview.findViewById(R.id.name);
				holder.pay = (TextView) convertview.findViewById(R.id.pay);
				holder.time = (TextView) convertview.findViewById(R.id.time);
				holder.states = (TextView) convertview
						.findViewById(R.id.status);
				convertview.setTag(holder);
			} else {
				holder = (viewHolder) convertview.getTag();
			}

			holder.name.setText(list.get(position).getLotteryname());
			float mon1 = Float.valueOf(list.get(position).getOrderpaymoney()) / 100;
			float mon2 = Float.valueOf(list.get(position).getOrderpayred()) / 100;
		Log.i("xxxxxxxxxxx", list.get(position).getOrderpayred());
			float mon = mon1 + mon2;
			df = new DecimalFormat("#0.00");
			String money = df.format(mon);

			holder.pay.setText(money + "元");
			holder.time.setText(list.get(position).getCtime());
			String status = list.get(position).getStatus();
			String tradestatus = list.get(position).getTradestatus();
			String issurepay = list.get(position).getIssurepay();
			String outime = list.get(position).getOuttime();
			if (outime.equals("false")) {
				if (issurepay.equals("0")) {
					holder.states.setText("未支付");
					holder.states.setTextColor(android.graphics.Color.RED);
				} else {
					if (tradestatus.equals("1")) {
						holder.states.setText("出票中");
						holder.states.setTextColor(android.graphics.Color.RED);
					} else if (tradestatus.equals("2")) {
						holder.states.setText("出票中");
						holder.states.setTextColor(android.graphics.Color.RED);
					} else if (tradestatus.equals("3")) {
						if (status.equals("0")) {
							holder.states.setText("待开奖");
							holder.states.setTextColor(android.graphics.Color.RED);
						} else if (status.equals("1")) {
							holder.states.setText("未中奖");
							holder.states.setTextColor(0xFFC0C0C0);
							
						} else {
							holder.states.setText("中奖");
							holder.states.setTextColor(android.graphics.Color.RED);
						}
					} else if ("4".equals(tradestatus)) {
						holder.states.setText("出票失败");
						holder.states.setTextColor(0xFFC0C0C0);
					}else if ("5".equals(tradestatus)) {
						holder.states.setText("部分出票失败");
						holder.states.setTextColor(0xFFC0C0C0);
					} else {
						holder.states.setText("部分出票失败");
					}
				}
			} else {
				holder.states.setText("已过期");
				holder.states.setTextColor(0xFFC0C0C0);
			}
			return convertview;
		}

		class viewHolder {
			TextView name, pay, time, states;
		}
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageSelected(int id) {
		switch (id) {
		case 0:
			tv_all.setCompoundDrawables(null, null, null, im_bottom);
			tv_no_open.setCompoundDrawables(null, null, null, null);
			tv_win.setCompoundDrawables(null, null, null, null);

			break;
		case 1:
			tv_all.setCompoundDrawables(null, null, null, null);
			tv_no_open.setCompoundDrawables(null, null, null, null);
			tv_win.setCompoundDrawables(null, null, null, im_bottom);

			break;
		case 2:
			tv_all.setCompoundDrawables(null, null, null, null);
			tv_no_open.setCompoundDrawables(null, null, null, im_bottom);
			tv_win.setCompoundDrawables(null, null, null, null);

			break;
		default:
			break;
		}

	}

	@Override
	public void onClick(View view) {

		switch (view.getId()) {
		case R.id.text1:
			viewPager.setCurrentItem(0);
			break;
		case R.id.text2:
			viewPager.setCurrentItem(1);
			break;
		case R.id.text3:
			viewPager.setCurrentItem(2);
			break;
		case R.id.tel:
			Intent intent = new Intent(MyLotterActivity.context,
					TelActivity.class);
			startActivity(intent);
			break;
		case R.id.btn_success_chongzhi:

			Intent intent1 = new Intent(MyLotterActivity.context,
					RechargeActivity.class);
			intent1.putExtra("money", tv_balance.getText().toString());
			startActivity(intent1);
			break;
		case R.id.btn_success_tixian:

			info = ((ThreadActivity) getActivity()).getLoginInfo();
			if (info.getVerify().equals("1")) {
				Intent intent2 = new Intent(MyLotterActivity.context,
						CashRequestActivity.class);
				intent2.putExtra("leftmoney", tv_balance.getText().toString());
				startActivity(intent2);
			} else {
				if (getActivity() != null) {

					Toast.makeText(getActivity(), "请先完善身份信息", 0).show();
					Intent intent3 = new Intent(getActivity(),
							CompleteUserInfoActivity.class);
					startActivity(intent3);
				}
			}

			break;

		case R.id.red_detail:

			Intent intent5 = new Intent(MyLotterActivity.context,
					RedPackeDetail.class);
			startActivity(intent5);
			break;

		case R.id.account:

			Intent intent4 = new Intent(MyLotterActivity.context,
					MyAccountActivity.class);
			startActivity(intent4);
			break;

		case R.id.login_success_wanshan:

			Intent intent3 = new Intent(getActivity(),
					CompleteUserInfoActivity.class);
			startActivity(intent3);

			break;
		case R.id.buy_lottery_tip:
			IConstants.localUserMoney = 0;
			Intent inent = new Intent(getActivity(), MainTabActivity.class);
			inent.putExtra("tag", "hall");
			startActivity(inent);
			break;
			//购买红包
		case R.id.red_packe:
			Intent intentred = new Intent(getActivity(), BuyRedpacketList.class);
			startActivity(intentred);
		default:
			break;
		}

	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

	}

}
